//
//  YHYAddViewController.m
//  Home
//
//  Created by 杨泓晔 on 16/4/27.
//  Copyright © 2016年 LanJue. All rights reserved.
//

#import "YHYCompanyViewController.h"
#import "YHYCompanyAddPictureCell.h"
#import "WSShopInfoNextView.h"
#import "DCPaymentView.h"
#import "WSCustomPickerView.h"
#import "AppDelegate.h"
#import "YHYSelectViewController.h"
#import "TZTestCell.h"
//#import "YHYSeaPictureViewController.h"
#import "TZImagePickerController.h"
//#import "UIView+Five.h"
#import "UIView+Layout.h"
#import "YHYDesignRequireTableViewCell.h"
#import "YHYStyleTableViewCell.h"
#import "YHYButtonTableViewCell.h"
#import "SeaPictureViewController.h"

#import "YHYPictureCollectionViewCell.h"
@interface YHYCompanyViewController ()<UITableViewDataSource,UITableViewDelegate,WSCustomPickerViewDelegate,UITableViewDelegate,UITableViewDataSource,YHYSelectViewDelegate,UICollectionViewDataSource,UICollectionViewDelegate,TZImagePickerControllerDelegate,YHYButtonTableViewdelegate,YHYCompanyAddPicturedelegate>{
    NSInteger index;
    CGFloat _itemWH;
    CGFloat _margin;
    
    NSMutableArray *_selectedAssets;
    
    NSInteger a;
    NSIndexPath *indexP;
    
    
    NSIndexPath *indexComP;//点击cell
}
@property (nonatomic,strong)UITableView *myTableView;
//@property (nonatomic,strong)NSArray *array;
//@property (nonatomic,strong)NSArray *arrTwo;
@property (nonatomic,strong)NSString *name;
@property (nonatomic,strong)WSCustomPickerView *customPicker;
@property (nonatomic,strong)NSString *styleRequire;

@property (nonatomic,strong)YHYSelectViewController *yhy;
//@property (nonatomic,retain)TZTestCell *cell;

@property (nonatomic,strong)AppDelegate *myAppDelegate;
@property (nonatomic,strong)UIView *myBackBigView;
//@property (nonatomic,strong)NSMutableArray *mycollectionVArray;


@property (nonatomic,assign)NSInteger selectArray;
@property (nonatomic,strong)UICollectionViewFlowLayout *layout;
@property (nonatomic,strong)UICollectionView *myCollectionView;
@property (nonatomic,strong)UILabel *numLabel;
@property (nonatomic,strong)UIButton *button;


@property (nonatomic,retain)NSIndexPath *myindexPath;
@property (nonatomic,retain)NSMutableArray *seaArr;
@property (nonatomic,retain)NSIndexPath *tapIndexPath;



@property (nonatomic, assign)BOOL lastIsHidden;
@property (nonatomic, strong)UILabel *animationLabel;

@end

@implementation YHYCompanyViewController

- (void)viewWillAppear:(BOOL)animated {
    
    //    self.navigationController.navigationBarHidden = NO;
    self.title = @"公司图片";
    self.tabBarController.tabBar.hidden = YES;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(change:) name:@"arr" object:nil];
    self.tabBarController.tabBar.hidden=YES;
    
    self.navigationController.navigationBar.translucent = YES;
    
    [self.myCollectionView reloadData];
}

-(void) viewWillDisappear:(BOOL)animated
{
    self.tabBarController.tabBar.hidden=NO;
}

- (void)viewDidLoad {
    [self creatView];
    
    self.selectedPhotos = [NSMutableArray array];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"back"] style:UIBarButtonItemStylePlain target:self action:@selector(Back:)];
    self.navigationItem.leftBarButtonItem.tintColor = [UIColor whiteColor];
    
    self.layout = [[UICollectionViewFlowLayout alloc] init];
    _margin = 4 * AUTO_HEIGHT;
    _itemWH = (self.view.tz_width - 20 * AUTO_WIDTH-2 * _margin - 7) / 3 - _margin;
    self.layout.itemSize = CGSizeMake(_itemWH, _itemWH  - 1 );
    self.layout.minimumInteritemSpacing = _margin;
    self.layout.minimumLineSpacing = 10  * AUTO_HEIGHT ;
    _myCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0 * AUTO_WIDTH, SCREEN_WIDTH, 150 * AUTO_HEIGHT  + (150 * AUTO_HEIGHT* (0))) collectionViewLayout:self.layout];
    
    
    
    _selectedAssets = [NSMutableArray array];
    self.myindexPath = [NSIndexPath new];
    _seaArr = [NSMutableArray array];
   // self.numLabel = [UILabel new];
    self.tapIndexPath = [NSIndexPath new];
    _myCollectionView.backgroundColor = [UIColor whiteColor];
    
    [_myTableView reloadData];
    // [_myCollectionView reloadData];
    
    
    
    
    self.animationLabel = [[UILabel alloc] init];
    self.animationLabel.textAlignment = NSTextAlignmentCenter;
    self.animationLabel.font = [UIFont systemFontOfSize:15];
    self.animationLabel.numberOfLines = 1;
    self.animationLabel.backgroundColor = [UIColor redColor];
    self.animationLabel.adjustsFontSizeToFitWidth = YES;
    self.animationLabel.minimumScaleFactor = 0.1;
    self.animationLabel.layer.borderWidth = 0.45;

    
}

- (void)creatView{
    
    self.myTableView = [UITableView new];
    
    [self.view addSubview:self.myTableView];
    self.myTableView.rowHeight = 50 * AUTO_HEIGHT;
    
    self.myTableView.separatorStyle = UITableViewCellSelectionStyleNone;
    
    
    [self.myTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.view);
        make.left.mas_equalTo(self.view);
        make.height.mas_equalTo(self.view.frame.size.height + 50 * AUTO_HEIGHT);
        make.width.mas_equalTo(self.view);
        
    }];
    //_myTableView.scrollEnabled = NO;
    self.myTableView.delegate = self;
    self.myTableView.dataSource = self;
    self.myTableView.backgroundColor = LV;
    [self.myTableView registerClass:[YHYCompanyAddPictureCell class] forCellReuseIdentifier:@"cell"];
    [self.myTableView registerClass:[YHYDesignRequireTableViewCell class] forCellReuseIdentifier:@"YHYDesignRequireTableViewCell"];
    [self.myTableView registerClass:[YHYStyleTableViewCell class] forCellReuseIdentifier:@"YHYStyleTableViewCell"];
    [self.myTableView registerClass:[YHYButtonTableViewCell class] forCellReuseIdentifier:@"YHYButtonTableViewCell"];
    [self.myTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"ce"];
    [[UITableViewHeaderFooterView appearance] setTintColor:LV];
    //    _myCollectionView.frame = CGRectMake(0, 0, SCREEN_WIDTH, 150 * AUTO_HEIGHT  + (150 * AUTO_HEIGHT* (a)));
    
    
    UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc]
                                               initWithTarget:self action:@selector(longPressGestureRecognized:)];
    [self.myTableView addGestureRecognizer:longPress];

   
    [_myCollectionView reloadData];
    [_myTableView reloadData];
    
}

//长按手势方法
- (void)longPressGestureRecognized:(id)sender {
    
    UILongPressGestureRecognizer *longPress = (UILongPressGestureRecognizer *)sender;
    UIGestureRecognizerState state = longPress.state;
    
    CGPoint location = [longPress locationInView:self.myTableView];
    NSIndexPath *indexPath = [self.myTableView indexPathForRowAtPoint:location];
    
    static UIView       *snapshot = nil;        ///< A snapshot of the row user is moving.
    static NSIndexPath  *sourceIndexPath = nil; ///< Initial index path, where gesture begins.
    
    switch (state) {
        case UIGestureRecognizerStateBegan: {
            if (indexPath) {
                sourceIndexPath = indexPath;
                
                YHYCompanyAddPictureCell *cell = (YHYCompanyAddPictureCell *)[self.myTableView cellForRowAtIndexPath:indexPath];
                
                
                // Take a snapshot of the selected row using helper method.
                snapshot = [self customSnapshotFromView:cell];
                
                // Add the snapshot as subview, centered at cell's center...
                __block CGPoint center = cell.center;
                snapshot.center = center;
                snapshot.alpha = 0.0;
                [self.myTableView addSubview:snapshot];
                [UIView animateWithDuration:0.25 animations:^{
                    
                    // Offset for gesture location.
                    center.y = location.y;
                    snapshot.center = center;
                    snapshot.transform = CGAffineTransformMakeScale(1.05, 1.05);
                    snapshot.alpha = 0.98;
                    
                    // Black out.
                    cell.backgroundColor = [UIColor blackColor];
                } completion:nil];
            }
            break;
        }
        case UIGestureRecognizerStateChanged: {
            CGPoint center = snapshot.center;
            center.y = location.y;
            snapshot.center = center;
            
            // Is destination valid and is it different from source?
            if (indexPath && ![indexPath isEqual:sourceIndexPath]) {
                
                // ... update data source.
                [self.selectedPhotos exchangeObjectAtIndex:indexPath.row withObjectAtIndex:sourceIndexPath.row];
                
                // ... move the rows.
                [self.myTableView moveRowAtIndexPath:sourceIndexPath toIndexPath:indexPath];
                
                // ... and update source so it is in sync with UI changes.
                sourceIndexPath = indexPath;
                
            }
            break;
        }
        default: {
            // Clean up.
            UITableViewCell *cell = [self.myTableView cellForRowAtIndexPath:sourceIndexPath];
            [UIView animateWithDuration:0.25 animations:^{
                
                snapshot.center = cell.center;
                snapshot.transform = CGAffineTransformIdentity;
                snapshot.alpha = 0.0;
                
                // Undo the black-out effect we did.
                cell.backgroundColor = [UIColor whiteColor];
                
            } completion:^(BOOL finished) {
                
                [snapshot removeFromSuperview];
                snapshot = nil;
                
            }];
            sourceIndexPath = nil;
            break;
        }
    }
    // More coming soon...
    
}
- (UIView *)customSnapshotFromView:(UIView *)inputView {
    
    UIView *snapshot = [inputView snapshotViewAfterScreenUpdates:YES];
    snapshot.layer.masksToBounds = NO;
    snapshot.layer.cornerRadius = 0.0;
    snapshot.layer.shadowOffset = CGSizeMake(-5.0, 0.0);
    snapshot.layer.shadowRadius = 5.0;
    snapshot.layer.shadowOpacity = 0.4;
    
    return snapshot;
}

#pragma mark - 协议

- (void)buttonAction:(UIButton *)button{
    YHYCompanyAddPictureCell *cell = (YHYCompanyAddPictureCell *)button.superview.superview;
    NSIndexPath *indexPath = [_myTableView indexPathForCell:cell];
    
    if (1001 == button.tag) {
        // 上
        
    
        if (0 == indexPath.row) {
            NSLog(@"到顶了");
        } else {
            [_selectedPhotos exchangeObjectAtIndex:indexPath.row withObjectAtIndex:indexPath.row - 1];
            
            //            NSArray *arr = @[
            //                             [NSIndexPath indexPathForItem:indexPath.row inSection:0],
            //                             [NSIndexPath indexPathForItem:indexPath.row - 1 inSection:0]];
            [_myTableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForItem:indexPath.row inSection:0]] withRowAnimation:UITableViewRowAnimationTop];
            [_myTableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForItem:indexPath.row - 1 inSection:0]] withRowAnimation:UITableViewRowAnimationTop];
        }
        

}
    
    if (1002 == button.tag) {
                if (_selectedPhotos.count- 1 == indexPath.row) {
            NSLog(@"到底部");
        }
        else{
        [_selectedPhotos exchangeObjectAtIndex:indexPath.row  withObjectAtIndex:indexPath.row + 1 ];
            [_myTableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForItem:indexPath.row+1 inSection:0]] withRowAnimation:UITableViewRowAnimationTop];
            [_myTableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForItem:indexPath.row inSection:0]] withRowAnimation:UITableViewRowAnimationTop];
        }
    }
    
    if (1000 == button.tag) {
        [_selectedPhotos removeObjectAtIndex:indexPath.row];
        [_myTableView reloadData];
    }
    
}



-(void) tableView: (UITableView *) tableView moveRowAtIndexPath: (NSIndexPath *) oldPath toIndexPath:(NSIndexPath *) newPath

{
    
           [self.myTableView reloadData];
}

//-(BOOL)tableView:(UITableView *) tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
//{
//    //打开编辑
//    return YES;
//}
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    //允许移动
    return YES;
    //return NO;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 3;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    
    if (section == 0) {
        return 0;
    }
    if (section == 1) {
        return 0;
    }
    if (section == 2) {
        return 0;
    }
    else{
    
    return 8 * AUTO_HEIGHT;
    }
}


//缩微图
- (UIImage *)imageByScalingProportionallyToSize: (CGSize)targetSize {
    
    UIImage *sourceImage = self;
    UIImage *newImage = nil;
    CGSize imageSize = sourceImage.size;
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;
    CGFloat targetWidth = targetSize.width;
    CGFloat targetHeight = targetSize.height;
    CGFloat scaleFactor = 0.0;
    CGFloat scaledWidth = targetWidth;
    CGFloat scaledHeight = targetHeight;
    CGPoint thumbnailPoint = CGPointMake(0.0,0.0);
    if (CGSizeEqualToSize(imageSize, targetSize) == NO) {
        CGFloat widthFactor = targetWidth / width;
        CGFloat heightFactor = targetHeight / height;
        if (widthFactor < heightFactor)
            scaleFactor = widthFactor;
        else
            scaleFactor = heightFactor;
        scaledWidth  = width * scaleFactor;
        scaledHeight = height * scaleFactor;
        
        // center the image
        if (widthFactor < heightFactor) {
            thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
        } else if (widthFactor > heightFactor) {
            thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
        }
    }
    // this is actually the interesting part:
    UIGraphicsBeginImageContext(targetSize);
    CGRect thumbnailRect = CGRectZero;
    thumbnailRect.origin = thumbnailPoint;
    thumbnailRect.size.width  = scaledWidth;
    thumbnailRect.size.height = scaledHeight;
    [sourceImage drawInRect:thumbnailRect];
    newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    if(newImage == nil) NSLog(@"could not scale image");
    return newImage ;
}
//-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
//    //转动特效
//    CATransform3D rotation;
//    rotation = CATransform3DMakeRotation( (90.0*M_PI)/180, 0.0, 0.7, 0.4);
//    rotation.m34 = 1.0/ -600;
//    
//    cell.layer.shadowColor = [[UIColor blackColor]CGColor];
//    cell.layer.shadowOffset = CGSizeMake(10, 10);
//    cell.alpha = 0;
//    cell.layer.transform = rotation;
//    cell.layer.anchorPoint = CGPointMake(0, 0.5);
//    
//    
//    [UIView beginAnimations:@"rotation" context:NULL];
//    [UIView setAnimationDuration:0.8];
//    cell.layer.transform = CATransform3DIdentity;
//    cell.alpha = 1;
//    cell.layer.shadowOffset = CGSizeMake(0, 0);
//    [UIView commitAnimations];
//    
//    [UIView animateWithDuration:0.5 animations:^{
//        cell.layer.transform = CATransform3DIdentity;
//        cell.alpha = 1;
//        cell.layer.shadowOffset = CGSizeMake(0, 0);
//    }];
//}
//

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        return _selectedPhotos.count;
    }
    
        return 1;
//    }
//    return 0;
    
   
    
}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *str = @"cell";
    
    if (indexPath.section == 0) {
        
        indexComP = indexPath;
    YHYCompanyAddPictureCell *cell2 = [tableView dequeueReusableCellWithIdentifier:str];
        
        [self imageCompressForSize:[_selectedPhotos objectAtIndex:indexPath.row] targetSize:CGSizeMake(-100, -100)];
    cell2.selectionStyle = UITableViewCellSelectionStyleNone;
        cell2.delegate = self;
//        cell2.myImageView.contentMode = UIViewContentModeRedraw;
//        [self generatePhotoThumbnail:[_selectedPhotos objectAtIndex:indexPath.row]];
        cell2.myImageView.image = [_selectedPhotos objectAtIndex:indexPath.row];
        
        

        
    return cell2;
    }
    
    if (indexPath.section == 1) {
    
    //图片
    
        UITableViewCell *cell3 = [tableView dequeueReusableCellWithIdentifier:@"ce" forIndexPath:indexPath];
        
        
        
        cell3.selectionStyle = UITableViewCellSelectionStyleNone;
        cell3.backgroundColor = LV;
        indexP = indexPath;
        
        
        
        
        //    裁掉view的边界
        self.myCollectionView.layer.masksToBounds = NO;
        //    设置半径
        //self.myCollectionView.layer.cornerRadius = 6 * AUTO_WIDTH;
        self.myCollectionView.scrollEnabled = NO;
        // self.myCollectionView.backgroundColor = [UIColor whiteColor];
     //  [self changeUICollectionView];
        [cell3 addSubview:_myCollectionView];
        
        
        _myCollectionView.contentInset = UIEdgeInsetsMake(13 * AUTO_WIDTH, 15 * AUTO_HEIGHT, 5 * AUTO_WIDTH, 15 * AUTO_HEIGHT);
        _myCollectionView.scrollIndicatorInsets = UIEdgeInsetsMake(0, 0, 0, -2 * AUTO_HEIGHT);
        _myCollectionView.dataSource = self;
        _myCollectionView.delegate = self;
        
        
     //   [self changeUICollectionView];
        [_myCollectionView registerClass:[TZTestCell class] forCellWithReuseIdentifier:@"TZTestCell"];
        
        [_myCollectionView registerClass:[YHYPictureCollectionViewCell class] forCellWithReuseIdentifier:@"YHYPicCollectionViewCell"];
      //  UILongPressGestureRecognizer *longGesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(buttonLongPressed:)];
    //    [_myCollectionView addGestureRecognizer:longGesture];
        
        
        
//        [cell3 addSubview:self.numLabel];
//        self.numLabel.textColor = [UIColor blackColor];
//        self.numLabel.alpha = 0.6;
//        self.numLabel.font = [UIFont systemFontOfSize:TEXTLABELFONT*TEXTWEIGHT];
//      //  [self changeUICollectionView];
//        
//        [self.numLabel mas_makeConstraints:^(MASConstraintMaker *make) {
//            make.top.mas_equalTo(_myCollectionView.mas_bottom).offset(11 * AUTO_HEIGHT);
//            make.left.mas_equalTo(cell3.mas_right).offset( - 50  * AUTO_WIDTH);
//            make.height.mas_equalTo(15 * AUTO_WIDTH);
//            
//            
//        }];
//        
//        self.numLabel.text = [NSString stringWithFormat:@"%ld/9",(long)_selectedPhotos.count];
//        [_myCollectionView reloadData];
        
        return cell3;
        
        
        
    //    self.numLabel.text = [NSString stringWithFormat:@"%ld/9",(long)_selectedPhotos.count];
        
        
    }
    if (indexPath.section == 2) {
        YHYButtonTableViewCell *cellb = [tableView dequeueReusableCellWithIdentifier:@"YHYButtonTableViewCell"];
        cellb.delegate = self;
        cellb.selectionStyle = UITableViewCellSelectionStyleNone;
        [cellb.button setTitle:@"保存" forState:UIControlStateNormal];
        return cellb;
    }
    return nil;
    
}






- (void)goNext:(UIButton *)btu{
    [self.navigationController popViewControllerAnimated:YES];
}
////UICollectionView长按响应
//- (void)buttonLongPressed:(UILongPressGestureRecognizer *)longPress
//{  [self changeUICollectionView];
//    switch (longPress.state) {
//        case UIGestureRecognizerStateBegan:
//        {
//            
//            NSIndexPath *selectedIndex = [[NSIndexPath alloc] init];
//            CGPoint point = [longPress locationInView:_myCollectionView];
//            selectedIndex = [_myCollectionView indexPathForItemAtPoint:point];
//            [_myCollectionView beginInteractiveMovementForItemAtIndexPath:selectedIndex];
//            TZTestCell *mycell = (TZTestCell *)[_myCollectionView cellForItemAtIndexPath:selectedIndex];
//            if (selectedIndex.row == _selectedPhotos.count) {
//                //左后一个不抖动
//            }
//            else{
//                [self shakeAnimationForView:mycell.imageView point:point];
//            }
//            
//        }
//            break;
//        case UIGestureRecognizerStateChanged:
//        {
//            [_myCollectionView updateInteractiveMovementTargetPosition:[longPress locationInView:_myCollectionView]];
//        }
//            break;
//        case UIGestureRecognizerStateEnded:
//        {
//            // 啥意思打上注释:就是当他移动时，到边距ok，移动到一定位置就删除
//            [_myCollectionView endInteractiveMovement];
//            NSIndexPath *selectedIndex = [[NSIndexPath alloc] init];
//            CGPoint point = [longPress locationInView:_myCollectionView];
//            
//            selectedIndex = [_myCollectionView indexPathForItemAtPoint:point];
//            
//            if (point.x < 50 || point.y < 50 || point.x > _itemWH * 3  - 30 || point.y > _itemWH * 3  - 40) {
//                //          是图片
//                [_selectedPhotos removeObjectAtIndex:_myindexPath.item];
//                //                _myCollectionView.frame = CGRectMake(0, 0, SCREEN_WIDTH, 150 * AUTO_HEIGHT  + (100 * AUTO_HEIGHT* (a)));
//                [self changeUICollectionView];
//                
//                //   [_selectedPhotos removeObject:selectObject];
//                //                 NSLog(@"%@",_selectedPhotos);
//                //                NSLog(@"zzzzzzz%ld",(unsigned long)_selectedPhotos.count);
//                
//                
//                // [_selectedPhotos removeObject:selectObject];
//                NSLog(@"asasasas%@",_selectedPhotos);
//                NSLog(@"zzzzzzz%ld",(unsigned long)_selectedPhotos.count);
//                self.numLabel.text = [NSString stringWithFormat:@"%ld/9",(long)_selectedPhotos.count];
//                //                NSLog(@"sssssssss%ld",(long)_myindexPath.row);
//                
//                
//                
//                
//                
//                
//                //
//                TZTestCell *mycell = (TZTestCell *)[_myCollectionView cellForItemAtIndexPath:[NSIndexPath indexPathForItem:_selectedPhotos.count inSection:0]];
//                mycell.imageView.image = [UIImage imageNamed:@"jia"];
//                [_myTableView reloadData];
//                [_myCollectionView reloadData];
//                
//            }
//            
//            
//        }
//            
//            break;
//        default:
//            [_myCollectionView cancelInteractiveMovement];
//            break;
//    }
//    
//    
//    
//    
//}





//通知响应方法
- (void)change:(NSNotification *)notification
{
    NSMutableArray *ar = [notification object];
    self.selectedPhotos = ar;
    NSLog(@"qqqq%@",ar);
    self.numLabel.text = [NSString stringWithFormat:@"%ld/9",(long)_selectedPhotos.count];
    [_myCollectionView reloadData];
    
}

#pragma mark - 发布协议
- (void)presentDelegate{
    [self.navigationController popViewControllerAnimated:YES];
}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
//    NSLog(@"number:%ld", _selectedPhotos.count);
//    if (_selectedPhotos.count >= 9) {
//        return _selectedPhotos.count;
//    }
//    else{
//        return _selectedPhotos.count + 1;
//        
//    }
    return 1;
    
    
    
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    
    TZTestCell *cell1 =  [collectionView dequeueReusableCellWithReuseIdentifier:@"TZTestCell" forIndexPath:indexPath];
    if (indexPath.row == _selectedPhotos.count && _selectedPhotos.count <= 9) {
        
        //        YHYPictureCollectionViewCell *cell1 = [collectionView   dequeueReusableCellWithReuseIdentifier:@"YHYPicCollectionViewCell" forIndexPath:indexPath];
        
        cell1.imageView.image = [UIImage imageNamed:@"jia"];
                return cell1;
    }
//    else{
//        TZTestCell *cell =  [collectionView dequeueReusableCellWithReuseIdentifier:@"TZTestCell" forIndexPath:indexPath];
//        
//        if (!_selectedPhotos.count == 0) {
//            cell.imageView.image = _selectedPhotos[indexPath.row];
//            
//            NSLog(@"-------%@", _selectedPhotos);
//        }
//        
//        //        cell.imageI = _selectedPhotos[indexPath.row];
//        
//        
//        return cell;
//        
//        
//        
//        
//    }
    
    
    return cell1;
    
   // [_myTableView reloadData];
    
    
    
}


- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
//    if (indexPath.row == _selectedPhotos.count) {
        
        
        [self pickPhotoButtonClick:nil];
//        
//    }
//    else{
//        //        YHYYHYYHYViewController *yhySeaVC = [YHYYHYYHYViewController new];
//        
//        SeaPictureViewController *yhySeaVC = [SeaPictureViewController new];
//        yhySeaVC.seaArray  = [NSMutableArray arrayWithArray:_selectedPhotos];
//        yhySeaVC.indexNumber = (NSInteger)indexPath.item;
//        
//        NSLog(@"sssssss%ld",yhySeaVC.indexNumber);
//        //        [self presentViewController:yhySeaVC animated:YES completion:^{
//        //
//        //
//        //        }];
//        //        [self.navigationController presentViewController:yhySeaVC animated:YES completion:^{
//        //
//        //
//        //        }];
//        //
//        [self.navigationController pushViewController:yhySeaVC animated:YES];
//        
//        
//        
//        
//    }
    
    
}
//- (BOOL)collectionView:(UICollectionView *)collectionView canMoveItemAtIndexPath:(NSIndexPath *)indexPath{
//    
//    
//    
//    _myindexPath = indexPath;
//    if ([collectionView numberOfItemsInSection:indexPath.section] <= 1) {
//        return NO;
//    }
//    if (indexPath.row == _selectedPhotos.count) {
//        return NO;
//    }
//    
//    return YES;
//}
//
//
//- (void)collectionView:(UICollectionView *)collectionView moveItemAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath
//{
//    
//    
//    _tapIndexPath = sourceIndexPath;
//    
//    
//    if (destinationIndexPath.row != _selectedPhotos.count) {
//        
//        
//        NSString *selectObject = _selectedPhotos[sourceIndexPath.item];
//        self.myindexPath = sourceIndexPath;
//        //从资源数组中移除该数据
//        [_selectedPhotos removeObject:selectObject];
//        
//        
//        
//        
//        
//        
//        NSMutableArray *destinationArr = _selectedPhotos;
//        [destinationArr insertObject:selectObject atIndex:destinationIndexPath.row];
//        _selectedPhotos = [NSMutableArray arrayWithArray:destinationArr];
//        
//    }else{
//#pragma mark -后改动的
//        
//        
//    }
//    
//    
//    [self changeUICollectionView];
//    [_myCollectionView reloadData];
//    [_myTableView reloadData];
//    
//    
//}



-(UIImage *) imageCompressForSize:(UIImage *)sourceImage targetSize:(CGSize)size{
    UIImage *newImage = nil;
    CGSize imageSize = sourceImage.size;
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;
    CGFloat targetWidth = size.width;
    CGFloat targetHeight = size.height;
    CGFloat scaleFactor = 0.0;
    CGFloat scaledWidth = targetWidth;
    CGFloat scaledHeight = targetHeight;
    CGPoint thumbnailPoint = CGPointMake(0.0, 0.0);
    if(CGSizeEqualToSize(imageSize, size) == NO){
        CGFloat widthFactor = targetWidth / width;
        CGFloat heightFactor = targetHeight / height;
        if(widthFactor > heightFactor){
            scaleFactor = widthFactor;
        }
        else{
            scaleFactor = heightFactor;
        }
        scaledWidth = width * scaleFactor;
        scaledHeight = height * scaleFactor;
        if(widthFactor > heightFactor){
            thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
        }else if(widthFactor < heightFactor){
            thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
        }
    }
    
    UIGraphicsBeginImageContext(size);
    
    CGRect thumbnailRect = CGRectZero;
    thumbnailRect.origin = thumbnailPoint;
    thumbnailRect.size.width = scaledWidth;
    thumbnailRect.size.height = scaledHeight;
    [sourceImage drawInRect:thumbnailRect];
    newImage = UIGraphicsGetImageFromCurrentImageContext();
    
    if(newImage == nil){
        NSLog(@"scale image fail");
    }
    
    UIGraphicsEndImageContext();
    
    return newImage;
}


#pragma mark Click Event

- (IBAction)pickPhotoButtonClick:(UIButton *)sender {
    //    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:5 delegate:self];
    NSInteger mum = 9;
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc]initWithMaxImagesCount:mum selectArr:_selectedPhotos delegate:self];
    imagePickerVc.selectCount = _selectedPhotos.count;
    //    NSLog(@"asas%ld",(long)imagePickerVc.selectCount);
    [self presentViewController:imagePickerVc animated:YES completion:nil];
    
   

  //  [self changeUICollectionView];
    [_myCollectionView reloadData];
    [_myTableView reloadData];
    
}


- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray *)photos sourceAssets:(NSArray *)assets{
    [_selectedPhotos addObjectsFromArray:photos];
    //  NSLog(@"wwww%ld",(unsigned long)photos.count);
    //[self configCollectionView];
    
    _myCollectionView.contentSize = CGSizeMake(0, ((_selectedPhotos.count + 2) / 3 ) * (_margin + _itemWH));
    
    
    self.numLabel.text = [NSString stringWithFormat:@"%ld/9",(long)_selectedPhotos.count];
 //   [self changeUICollectionView];
    [_myTableView reloadData];
    [_myCollectionView reloadData];
    
    
}

//- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
//    
//    
//    return CGSizeMake(_itemWH, _itemWH);
//    
//}
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    return UIEdgeInsetsMake(0, 0, 2.0 * AUTO_WIDTH, 0);
}





//
//- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
//    
////    if (indexPath.section == 0) {
//        YHYCompanyAddPictureCell *cell1 = (YHYCompanyAddPictureCell *)[_myTableView cellForRowAtIndexPath:indexPath];
//    
//    [UIView animateWithDuration:0.2 animations:^{
//        cell1.deleteButton.backgroundColor = [UIColor redColor];
//        
//    }];
//    
//    [_myTableView reloadData];
//
//        }
//    

    

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section==0) {
        if (_selectedPhotos.count != 0) {

        //  if (indexPath.row == 0) {
        return (580/3 + 150/3) * AUTO_HEIGHT;
          }
        
    }
       if (indexPath.section == 1) {
        
//        
//        //        NSInteger b = _selectedPhotos.count;
//        if (_selectedPhotos.count < 3 ) {
//            a = 0;
//            
//        }
//        if (_selectedPhotos.count >= 3 && _selectedPhotos.count <= 5) {
//            
//            a = 1;
//        }
//        if ( _selectedPhotos.count > 5 && _selectedPhotos.count <= 9) {
//            a = 2;
//        }
           return 150 * AUTO_HEIGHT  ;
    }
     //  [self changeUICollectionView];
    [_myCollectionView reloadData];
    
    
    // return 470 * AUTO_HEIGHT;
    
    if (indexPath.section == 2) {
        return 140 * AUTO_HEIGHT;
    }
    return 0;
}


//- (void)changeUICollectionView{
//    
//    if (_selectedPhotos.count < 3 ) {
//        a = 0;
//        
//    }
//    if (_selectedPhotos.count >= 3 && _selectedPhotos.count <= 5) {
//        
//        a = 1;
//    }
//    if ( _selectedPhotos.count > 5 && _selectedPhotos.count <= 9) {
//        a = 2;
//    }
//    
//    
//    _myCollectionView.frame = CGRectMake(0, 0, SCREEN_WIDTH, 150 * AUTO_HEIGHT  + (110 * AUTO_HEIGHT* (a))- 0 * AUTO_HEIGHT * (a));
//    
//    
//}


//- (void)shakeAnimationForView:(UIView *)view point:(CGPoint)point{
//    //获取到当前的View
//    CALayer *viewLayer = view.layer;
//    //获取当前View位置
//    CGPoint position = viewLayer.position;
//    CGPoint x = CGPointMake(position.x + 9, position.y);
//    CGPoint y = CGPointMake(position.x - 9, position.y);
//    
//    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"position"];
//    [animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionDefault]];
//    [animation setFromValue:[NSValue valueWithCGPoint:x]];
//    [animation setToValue:[NSValue valueWithCGPoint:y]];
//    [animation setAutoreverses:YES];
//    [animation setDuration:0.06];
//    [animation setRepeatCount:3];
//    [viewLayer addAnimation:animation forKey:nil];
//    
//    
//    
//}


- (void)Back:(UIButton*)btu{
    [self.navigationController popViewControllerAnimated:YES];
}

@end
